package com.example.rocketmqdemo2.demos.web.controller;


import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/msg")
@Slf4j
public class RocketMQController {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("/sendTest")
    public Object sendTest() {
//        同步、异步、单向消息发送测试
        // 同步发送消息，底层调用的syncSend方法
        rocketMQTemplate.convertAndSend("TopicTest", "Hello, World! I was sent by convertAndSend");

        // 发送一个Spring Message
        rocketMQTemplate.send("TopicTest", MessageBuilder.withPayload("Hello, World! I'm from spring message").build());

        // 异步发送消息
        Map<String,Object> obj = new HashMap<>();
        obj.put("id",1);
        obj.put("name","Long");
        rocketMQTemplate.asyncSend("TopicTest", obj, new SendCallback() {
            @Override
            public void onSuccess(SendResult var1) {
                log.warn("async onSucess SendResult={}", var1);
            }
            @Override
            public void onException(Throwable var1) {
                log.warn("async onException Throwable={}", var1);
            }
        });

        // 有序发送消息 - sync
        rocketMQTemplate.syncSendOrderly("OrderlyTopicTest",MessageBuilder.withPayload("Message 1. I was sent by syncSendOrderly").build(),"hashkey1");

        // 有序发送消息 - async
        rocketMQTemplate.asyncSendOrderly("OrderlyTopicTest",MessageBuilder.withPayload("Message 2. I was sent by asyncSendOrderly").build(),"hashkey1",new SendCallback() {
            @Override
            public void onSuccess(SendResult var1) {
                log.warn("async orderly onSucess SendResult={}", var1);
            }

            @Override
            public void onException(Throwable var1) {
                log.warn("async orderly onException Throwable={}", var1);
            }

        });
        // 注意:  只要调用了rocketMQTemplate的destroy方法, 就无法使用这个rocketMQTemplate发送消息了。注入的rocketMQTemplate需要特别注意。
        //rocketMQTemplate.destroy();
        return "success";
    }

    @RequestMapping("/sendListTest")
    public Object sendListTest() {
           for (int i = 0; i < 10; i++) {
               rocketMQTemplate.syncSend("TopicTest", "消息  " + i + "  " + IdUtil.getSnowflake(1, 1).nextId());
           }



        return "success";
    }
}